package com.hsmpay.mobile.action.added.marhui;

import com.hsmpay.common.pojo.user.User;
import com.hsmpay.common.util.JSONStringBuilder;
import com.hsmpay.common.util.jiami.HttpClientUtils;
import com.hsmpay.mobile.action.base.MobileBaseAction;
import com.hsmpay.mobile.pojo.user.UserAdded;
import com.hsmpay.mobile.service.user.UserAddedService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 马融汇 action
 *
 * @author 颜铃璋
 * @date 2015-4-27
 */
@Controller("marhuiAction")
@Scope("prototype")
public class MarhuiAction extends MobileBaseAction {
    private static final long serialVersionUID = -4209437170500467527L;
    private static Logger log = Logger.getLogger(MarhuiAction.class);

    @Resource(name = "userAddedService")
    private UserAddedService<UserAdded, Long> userAddedService;

    public String marhuiUrl = "http://www.marhui.com/proOneMobile/forward/fcn.do";


    /**
     * 检查马融汇用户是否可用
     *
     * @return
     * @throws Exception
     */
    public String checkUser() throws Exception {
        log.debug("--- checkUser() start ---");
        clientType = Integer.parseInt(getJsonString("clientType"));
        terminalTypeId = Long.parseLong(getJsonString("terminalTypeId"));
        roleId = Long.parseLong(getJsonString("roleId"));
        if (StringUtils.isNotEmpty(getJsonString("userId")))
            userId = Long.parseLong(getJsonString("userId"));

        log.debug("clientType = " + clientType);
        log.debug("terminalTypeId = " + terminalTypeId);
        log.debug("roleId = " + roleId);
        log.debug("userId = " + userId);

        if (null == userId) {
            log.info("检查马融汇用户是否可用时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }

        try {
            Map<String, Object> result = new LinkedHashMap<String, Object>();
            JSONObject marhuiJson = null;
            UserAdded userAdded = userAddedService.searchUserAddedByUserId(userId, 1);
            //到马融汇检查  用户是否可以
            Map<String, Object> param = new LinkedHashMap<String, Object>();
            param.put("action", "marhuiAction_checkUser");
            param.put("clientType", clientType);
            param.put("terminalTypeId", terminalTypeId);
            param.put("roleId", roleId);
            param.put("userId", userId);
            String jsonStr = HttpClientUtils.httpClientUtils(JSONStringBuilder.getAjaxString(param), marhuiUrl, HttpClientUtils.marhuiPublicKey);
            JSONObject json = JSONObject.fromObject(jsonStr);
            if ("0000".equals(json.getString("reqCode")) && json.containsKey("marhui")) {
                String marhui = json.getString("marhui").toString();
                marhuiJson = JSONObject.fromObject(marhui);

                if (null == userAdded) {
                    userAdded = new UserAdded();
                    userAdded.setUserId(userId);
                    userAdded.setType(1);
                    userAdded.setReqCode(json.getString("reqCode"));
                    userAdded.setReqMsg(json.getString("reqMsg"));
                    userAddedService.insertEntity(userAdded);
                } else {
                    if (!marhui.equals(userAdded.getOtherData())) {
                        userAdded.setReqCode(json.getString("reqCode"));
                        userAdded.setReqMsg(json.getString("reqMsg"));
                        userAdded.setOtherData(marhui);
                        userAddedService.updateEntity(userAdded);
                    }

                }
                result.put("reqCode", json.getString("reqCode"));
                result.put("reqMsg", json.getString("reqMsg"));
                result.put("marhui", marhuiJson);
            } else {
                result.put("reqCode", "0001");
                result.put("reqMsg", "检查马融汇用户是否可用时,访问理财接口未知错误！");
                result.put("marhui", "");
            }
            sendAppMsg(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return null;
    }

    /**
     * 绑定马融汇
     *
     * @return
     * @throws Exception
     */
    public String bindingMarhui() throws Exception {
        log.debug("--- bindingMarhui() start ---");
        clientType = Integer.parseInt(getJsonString("clientType"));
        terminalTypeId = Long.parseLong(getJsonString("terminalTypeId"));
        roleId = Long.parseLong(getJsonString("roleId"));
        if (StringUtils.isNotBlank(getJsonString("userId")))
            userId = Long.parseLong(getJsonString("userId"));

        log.debug("clientType = " + clientType);
        log.debug("terminalTypeId = " + terminalTypeId);
        log.debug("roleId = " + roleId);
        log.debug("userId = " + userId);
        if (null == userId) {
            log.info("绑定马融汇时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }

        try {
            Map<String, Object> result = new LinkedHashMap<String, Object>();
            JSONObject marhuiJson = null;
            User user = userService.getUserById(userId);
            if (null != user) {
                UserAdded userAdded = userAddedService.searchUserAddedByUserId(userId, 1);
                if (null != userAdded) {
                    if (StringUtils.isNotEmpty(userAdded.getOtherData())) {
                        JSONObject js1 = JSONObject.fromObject(userAdded.getOtherData());
                        if ("-1".equals(js1.get("error"))) {
                            result.put("reqCode", "0001");
                            result.put("reqMsg", "绑定马融汇，已经绑定了！");
                            result.put("marhui", userAdded.getOtherData());
                            sendAppMsg(result);
                            return null;
                        }
                    }
                }
                Map<String, Object> param = new LinkedHashMap<String, Object>();
                param.put("action", "marhuiAction_bindingMarhui");
                param.put("clientType", clientType);
                param.put("terminalTypeId", terminalTypeId);
                param.put("roleId", roleId);
                param.put("userId", userId);
                String jsonStr = HttpClientUtils.httpClientUtils(JSONStringBuilder.getAjaxString(param), marhuiUrl, HttpClientUtils.marhuiPublicKey);
                JSONObject json = JSONObject.fromObject(jsonStr);
                if ("0000".equals(json.getString("reqCode")) && json.containsKey("marhui")) {
                    String marhui = json.getString("marhui").toString();
                    marhuiJson = JSONObject.fromObject(marhui);

                    if (null != userAdded) {
                        userAdded.setOtherData(marhui);
                        userAdded.setReqCode(json.getString("reqCode"));
                        userAdded.setReqMsg(json.getString("reqMsg"));
                        userAddedService.updateEntity(userAdded);
                    } else {
                        userAdded = new UserAdded();
                        userAdded.setUserId(userId);
                        userAdded.setType(1);
                        userAdded.setReqCode(json.getString("reqCode"));
                        userAdded.setReqMsg(json.getString("reqMsg"));
                        userAdded.setOtherData(marhui);
                        userAddedService.insertEntity(userAdded);
                    }

                    result.put("reqCode", json.getString("reqCode"));
                    result.put("reqMsg", json.getString("reqMsg"));
                    result.put("marhui", marhuiJson);
                } else {
                    result.put("reqCode", "0002");
                    result.put("reqMsg", "绑定马融汇时,访问理财接口未知错误！");
                    result.put("marhui", "");
                }
                sendAppMsg(result);

            } else {
                log.warn("绑定马融汇时, 用户Id=" + userId + " 对应的用户不存在!");
                sendAppErrorMsg("6012", userId + "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return null;
    }

    /**
     * 取消绑定马融汇
     *
     * @return
     * @throws Exception
     */
    public String cancelBindingMarhui() throws Exception {
        log.debug("--- cancelBindingMarhui() start ---");
        clientType = Integer.parseInt(getJsonString("clientType"));
        terminalTypeId = Long.parseLong(getJsonString("terminalTypeId"));
        roleId = Long.parseLong(getJsonString("roleId"));
        if (StringUtils.isNotBlank(getJsonString("userId")))
            userId = Long.parseLong(getJsonString("userId"));

        log.debug("clientType = " + clientType);
        log.debug("terminalTypeId = " + terminalTypeId);
        log.debug("roleId = " + roleId);
        log.debug("userId = " + userId);
        if (null == userId) {
            log.info("取消绑定马融汇时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }

        try {
            Map<String, Object> result = new LinkedHashMap<String, Object>();
//			ngy

            User user = userService.getUserById(userId);
            if (null != user) {
                UserAdded userAdded = userAddedService.searchUserAddedByUserId(userId, 1);
                if (null == userAdded) {
                    result.put("reqCode", "0001");
                    result.put("reqMsg", "检查马融汇，未绑定马融汇！");
                    result.put("marhui", "");
                    sendAppMsg(result);
                } else {
                    //到马融汇检查  用户是否可以
                    Map<String, Object> param = new LinkedHashMap<String, Object>();
                    param.put("action", "marhuiAction_cancelBindingMarhui");
                    param.put("clientType", clientType);
                    param.put("terminalTypeId", terminalTypeId);
                    param.put("roleId", roleId);
                    param.put("userId", userId);
                    String jsonStr = HttpClientUtils.httpClientUtils(JSONStringBuilder.getAjaxString(param), marhuiUrl, HttpClientUtils.marhuiPublicKey);
                    JSONObject json = JSONObject.fromObject(jsonStr);
                    if ("0000".equals(json.getString("reqCode"))) {
                        userAddedService.deleteEntity(userAdded);
                    }
                    sendAppMsg(param);
                }
                sendAppMsg(result);
            } else {
                log.warn("取消绑定马融汇时, 用户Id=" + userId + " 对应的用户不存在!");
                sendAppErrorMsg("6012", userId + "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return null;
    }
}
